package org.to_zero.springboot.jwt.service.impl;

import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.to_zero.springboot.jwt.entity.SysAuth;
import org.to_zero.springboot.jwt.entity.SysUser;
import org.to_zero.springboot.jwt.mapper.SysUserMapper;

import java.util.List;
import java.util.Objects;

@Service("userDetailService")
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private SysUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Assert.notNull(username,"用户名不能为空");
        SysUser user = new LambdaQueryChainWrapper<>(userMapper).eq(SysUser::getUsername, username).one();
        if (Objects.isNull(user)) throw new UsernameNotFoundException("用户名或密码错误，请重新输入！");
        List<SysAuth> auths = userMapper.findAuthByUserId(user.getId());
        user.setAuths(auths);
        return user;
    }
}
